<?php

namespace mpend\models;

use Yii;
use yii\base\Exception;
use common\models\ThirdPartyAuthorization;
use common\helpers\ArrayHelper;
use common\models\app\AppToken;
use common\models\user\UserConnect;
use mpend\modules\share\models\SpreadAttractForm;

/**
 * APP接口访问授权接口
 * Authorization
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AuthorizationWechatForm extends ThirdPartyAuthorization {

    /**
     * @var string STATE
     */
    public $state;

    /**
     * @var array 终端访问信息
     */
    public $data;

    /**
     * @var array 终端访问信息
     */
    public $spread;

    /**
     * @var array 终端访问信息
     */
    public $connect;

    /**
     * @var array 终端访问信息
     */
    private $_userConnect = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return ArrayHelper::merge(parent::rules(), [
            [['data', 'state', 'spread', 'connect'], 'safe'],
            [['data'], 'validateData'],
            [['connect'], 'validateConnect'],
        ]);
    }

    /**
     * 校验请求的签名
     * @param string $attribute `sign`
     */
    public function validateData($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if ($this->token) {
            return;
        }
        $data = $this->$attribute;
        if (!empty($data)) {
            $model = new AuthorizationForm();
            Yii::error($data);
            $model->load($data, '');
            try {
                $this->token = $model->authorize();
            } catch (Exception $e) {
                Yii::error($e->getMessage());
                $this->addError($attribute, '接口授权失败');
            }
        }
    }

    /**
     * 校验请求的签名
     * @param string $attribute `sign`
     */
    public function validateConnect($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $connect = $this->$attribute;
        if (empty($connect)) {
            return;
        }
        $this->_userConnect = UserConnect::findOne($connect['id']);
    }

    /**
     * Signs user up.
     * @return User|null the saved model or null if saving fails
     */
    public function authorize() {
        if (!$this->validate()) {
            return $this->dumpError('授权参数校验失败');
        }
        /* @var $auth UserConnect|false */
        $auth = $this->_userConnect;
        if (!$auth) {
            $auth = $this->authent();
        }
        if ($auth === false && !($auth instanceof UserConnect)) {
            return $this->dumpError('授权获取失败');
        }
        /* @var $token AppToken */
        $token = $this->token;

        if ($token) {
            if ($this->spread) {
                Yii::error([
                    $this->spread,
                    $token
                ]);
                $spreadAttract = new SpreadAttractForm();
                $spreadAttract->user_id = $this->spread;
                $spreadAttract->token = $token;
                $spreadAttract->connect_id = $auth->id;
                $spreadAttract->bind();
            }
            // 1. 当前登录的用户，未绑定微信的，自动绑定
            if ($token->user_id && !$auth->user_id) {
                $auth->user_id = $token->user_id;
                if (!$auth->save()) {
                    return $this->dumpError('授权绑定用户失败');
                }
            }
            // 2. 当前登录的用户，如果绑定的微信的用户和当前用户不一致，则抛出异常
            if ($token->user_id && $auth->user_id != $token->user_id) {
                return $this->dumpError('当前微信已绑定了其他帐号，请直接使用微信授权登录');
            }
            // 3. 如果微信已绑定用户，并且用户已经绑定了手机号的
            if ($auth->user_id && $auth->user && $auth->user->mobile) {
                // 将用户授权绑定至接口token上
                if (!$token->bindUser($auth->user_id)) {
                    $this->dumpError('授权信息Token绑定失败');
                }
                // 绑定用户分支
                $token->joinBranch($auth->user_id);
            }
        }

        $wechatJsData = null;
        if (YII_ENV_PROD) {
            try {
                /* @var $wechat \common\components\wechat\MpWechat */
                $wechat = Yii::$app->wechat;
                $jsApiTicket = $wechat->getJsApiTicket();
                $wechatJsData = [
                    'appId' => $wechat->appId,
                    'jsapi_ticket' => $jsApiTicket,
                ];
            } catch (Exception $exc) {
                Yii::error($exc->getMessage(), __METHOD__);
            }
        } else {
            $wechatJsData = [
                'appId' => 'wwwwww',
                'jsapi_ticket' => 'aaaaa',
            ];
        }

        return [
            'token' => $token,
            'connect' => [
                'id' => $auth->id,
                'sdk' => $wechatJsData,
            ],
        ];
    }

}
